#ifndef _TCP_SERVER_HPP
#define _TCP_SERVER_HPP

#include <iostream>
#include <cstring>
#include <error.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h> // struct sockaddr_in
#include <unistd.h>
#include <pthread.h>
#include "Log.hpp"

/* 设计成单例模式
 * 添加双检锁
 */
class TcpServer
{
  private:
    enum {BACKLOG = 5};
    uint16_t port; // 端口号
    int listen_sock;
    static TcpServer* svr;

    TcpServer(const TcpServer&) = delete;
    TcpServer& operator=(const TcpServer&) = delete;
  public:
    TcpServer(uint16_t _port)
      :port(_port), listen_sock(-1)
    {}

    static TcpServer* Getinstance(uint16_t _port)
    {
        // 初始化static的mutex
        static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
        if(nullptr == svr)
        {
            pthread_mutex_lock(&mtx);
            if(nullptr == svr)
            {
                svr = new TcpServer(_port); 
                if(svr == nullptr) LOG(FATAL, "bad alloc");
            }
            pthread_mutex_unlock(&mtx);
        }

        return svr;
    }

    void InitServer()
    {
        Socket();
        Bind();
        Listen();
    }

    void Socket()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_sock == -1)
        {
            LOG(FATAL, strerror(errno));
            exit(2);
        }

        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO, "create socket ... success");
    }
    
    void Bind()
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sock, reinterpret_cast<struct sockaddr*>(&local), sizeof(local)) == -1)
        {
            LOG(FATAL, strerror(errno));
            exit(3);
        }
        LOG(INFO, "bind socket ...  success");
    }
    
    void Listen(int backlog = BACKLOG)
    {
        if(listen(listen_sock, backlog) == -1)
        {
            LOG(FATAL, strerror(errno));
            exit(4);
        }
        LOG(INFO, "listen socket ... success");
    }

    int Sock()
    {
        return listen_sock;
    }
    
    ~TcpServer()
    {
        if(listen_sock >= 0) close(listen_sock);
    }
};

TcpServer* TcpServer::svr = nullptr;

#endif
